package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImplimpl implements DishService {
    @Autowired
    private  DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private  SetmealDishMapper SetmealDishMapper;

    /**
     * 新增菜品
     * @param dto
     */
    @Override
    @Transactional
    public void addDish(DishDTO dto) {
        //构造菜品基本信息数据，并将其存入dish表中
        Dish dish = new Dish();
        //对象属性拷贝
        BeanUtils.copyProperties(dto,dish);
        dishMapper.insert(dish);
        log.info("dishId={}",dish.getId());

        Long dishId =dish.getId();//获取insert语句生成的主键值
        //2.构造菜品口味数据，并将其存入dish_flavor表中
        List<DishFlavor> dishFlavors = dto.getFlavors();
        if (dishFlavors!=null && dishFlavors.size()>0){
            dishFlavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page= dishMapper.list(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //判断是否启售
        ids.forEach(id->{
            Dish dish=dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new SetmealEnableFailedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //判断是否关联套餐
        List<Long> setmealDishIds = SetmealDishMapper.getSetmealDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
        dishMapper.deleteBatch(ids);
        //删除菜品关联的口味数据
        dishFlavorMapper.deleteBatch(ids);
    }

    /**
     * 回显菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();
        //根据id查询菜品信息
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish,dishVO);
        //根据id查询口味列表数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavorList);
        //返回
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional
    public void update(DishDTO dto) {
        //修改菜品基本信息dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        //修改口味表dish_flavor表
        //由于口味数据可能会新增，也可能会删除，可以修改，所以需要先删除后插入
        dishFlavorMapper.deleteByDishId(dto.getId());
        List<DishFlavor> dishFlavors = dto.getFlavors();
        if (dishFlavors!=null && dishFlavors.size()>0){
            dishFlavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(dishFlavors);
        }

    }

    /**
     * 启用禁用菜品
     * @param status
     * @param id
     */
    @Override
    public void enableOrDisable(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {
        DishPageQueryDTO dto = DishPageQueryDTO.builder()
                .categoryId(categoryId)
                .build();
        return dishMapper.list(dto);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBydish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
